﻿using System;
using ComponentSystem;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using YooAssetsSystem;

namespace LubanSystem
{
    /// <summary>
    /// YooAssets支持组件
    /// </summary>
    public partial class YooAssets_Com : ComponentWithId
    {
        
    }
    
    public partial class YooAssets_Com
    {
        /// <summary>
        /// 检查资源是否存在
        /// </summary>
        /// <param name="assetPath">资源路径</param>
        /// <param name="pkgName">包体名称</param>
        /// <returns>是否存在</returns>
        public bool Exist(string assetPath, string pkgName)
        {
            if (YAService_Entity.Instance == null)
            {
                Debug.LogError($"LubanSystem YooAssets_Com Exist yooAssetService 为空");
                return false;
            }

            if (string.IsNullOrEmpty(assetPath))
            {
                Debug.LogError($"LubanSystem YooAssets_Com Exist assetName或pkgName 为空 assetPath:{assetPath}");
                return false;
            }
            
            bool isExist = YAService_Entity.Instance.CheckLocationValid(assetPath, pkgName);
            return isExist;
        }
        
        /// <summary>
        /// 加载配置文件 -- 同步
        /// </summary>
        /// <param name="assetPath">资源路径</param>
        /// <param name="pkgName">包体名称</param>
        /// <returns>配置文件内容</returns>
        public string LoadConfig_Sync(string assetPath, string pkgName)
        {
            if (!this.Exist(assetPath, pkgName)) return string.Empty;

            string configData = string.Empty;

            TextAsset ta = YAService_Entity.Instance.LoadTextAsset_Sync(assetPath, pkgName);

            if (ta == null)
            {
                Debug.LogError($"LubanSystem YooAssets_Com Exist TextAsset 为空 -- assetPath:{assetPath} -- pkgName:{pkgName}");
                return string.Empty;
            }

            configData = ta.text;

            return configData;
        }

        /// <summary>
        /// 加载配置文件 -- 异步
        /// </summary>
        /// <param name="assetPath">资源路径</param>
        /// <param name="pkgName">包体名称</param>
        /// <returns>配置文件内容</returns>
        public async UniTask<string> LoadConfig_Async(string assetPath, string pkgName)
        {
            if (!this.Exist(assetPath, pkgName)) return string.Empty;

            string configData = string.Empty;

            TextAsset ta = await YAService_Entity.Instance.LoadTextAsset_Async(assetPath, pkgName);

            if (ta == null)
            {
                Debug.LogError($"LubanSystem YooAssets_Com Exist TextAsset 为空 -- assetPath:{assetPath} -- pkgName:{pkgName}");
                return string.Empty;
            }

            configData = ta.text;

            return configData;
        }
    }
}